package com.keyidea.jfxui.core.system;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.keyidea.jfxui.core.constant.UserConstants;
import com.keyidea.jfxui.core.page.TableDataInfo;
import com.keyidea.jfxui.core.system.domain.AjaxResult;
import com.keyidea.jfxui.core.system.sqlite.entity.SysDept;
import com.keyidea.jfxui.core.system.sqlite.entity.SysRole;
import com.keyidea.jfxui.core.system.sqlite.entity.SysUser;
import com.keyidea.jfxui.core.system.sqlite.entity.SysUserRole;
import com.keyidea.jfxui.core.system.sqlite.mapper.SysRoleMapper;
import com.keyidea.jfxui.core.system.sqlite.mapper.SysUserMapper;
import com.keyidea.jfxui.core.system.sqlite.mapper.SysUserRoleMapper;
import com.keyidea.jfxui.core.util.PasswordUtils;
import com.keyidea.jfxui.core.util.StringUtils;
import com.keyidea.jfxui.core.util.TokenUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class SysUserService extends BaseService {

    private final SysUserMapper sysUserMapper;

    private final SysRoleMapper sysRoleMapper;

    private final SysUserRoleMapper sysUserRoleMapper;

    private final SysDepartmentService sysDepartmentService;

    /**
     * 获取用户列表
     */
    public TableDataInfo list(Map<String, Object> query) {
        startPage(query);
        SysUser param = BeanUtil.toBean(query, SysUser.class);
        List<SysUser> list = sysUserMapper.selectUserList(param);
        return getDataTable(list);
    }

    public SysUser info(String username) {
        return sysUserMapper.selectUserByUserName(username);
    }

    /**
     * 根据用户编号获取详细信息
     */
    public AjaxResult getInfo(Long userId) {
        checkUserDataScope(userId);
        AjaxResult ajax = AjaxResult.success();
        List<SysRole> roles = sysRoleMapper.selectRoleAll();
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        if (StringUtils.isNotNull(userId)) {
            SysUser sysUser = sysUserMapper.selectUserById(userId);
            ajax.put(AjaxResult.DATA_TAG, sysUser);
            ajax.put("roleIds", sysUser.getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList()));
        }
        return ajax;
    }

    /**
     * 新增用户
     */
    public AjaxResult add(SysUser user) {
        //deptService.checkDeptDataScope(user.getDeptId());
        //roleService.checkRoleDataScope(user.getRoleIds());
        if (!checkUserNameUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !checkPhoneUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !checkEmailUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setCreateBy(getUsername());
        user.setPassword(PasswordUtils.encryptPassword(user.getPassword()));
        return toAjax(insertUser(user));
    }

    /**
     * 修改用户
     */
    public AjaxResult edit(SysUser user) {
        boolean b = checkUserAllowed(user);
        if (!b) {
            return error("不允许操作超级管理员用户");
        }
        checkUserDataScope(user.getUserId());
//        deptService.checkDeptDataScope(user.getDeptId());
//        roleService.checkRoleDataScope(user.getRoleIds());
        if (!checkUserNameUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !checkPhoneUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !checkEmailUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(getUsername());
        return toAjax(updateUser(user));
    }

    /**
     * 删除用户
     */
    public AjaxResult remove(String userIds) {
        Long[] userIdArray = Convert.convert(Long[].class, StrUtil.splitTrim(userIds, ","));
//        if (ArrayUtils.contains(userIds, getUserId()))
//        {
//            return error("当前用户不能删除");
//        }

        return toAjax(deleteUserByIds(userIdArray));
    }

    /**
     * 重置密码
     */
    public AjaxResult resetPwd(SysUser user) {
        checkUserAllowed(user);
        checkUserDataScope(user.getUserId());
        user.setPassword(PasswordUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(getUsername());
        return toAjax(sysUserMapper.updateUser(user));
    }

    /**
     * 状态修改
     */
    public AjaxResult changeStatus(SysUser user) {
        checkUserAllowed(user);
        checkUserDataScope(user.getUserId());
        user.setUpdateBy(getUsername());
        return toAjax(sysUserMapper.updateUser(user));
    }

    /**
     * 根据用户编号获取授权角色
     */
    public AjaxResult authRole(Long userId) {
        AjaxResult ajax = AjaxResult.success();
        SysUser user = sysUserMapper.selectUserById(userId);
        List<SysRole> roles = selectRolesByUserId(userId);
        ajax.put("user", user);
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return ajax;
    }

    /**
     * 用户授权角色
     */
    public AjaxResult insertAuthRole(Map<String, Object> query) {
        Long userId = (Long) query.get("userId");
        String roleIdsStr = (String) query.get("roleIds");
        Long[] roleIds = Convert.convert(Long[].class, StrUtil.splitTrim(roleIdsStr, ","));
        checkUserDataScope(userId);
//        checkRoleDataScope(roleIds);
        insertUserAuth(userId, roleIds);
        return success();
    }

    /**
     * 获取部门树列表
     */
    public AjaxResult deptTree(Map<String, Object> query) {
        SysDept param = BeanUtil.toBean(query, SysDept.class);
        return success(sysDepartmentService.selectDeptTreeList(param));
    }

    public void checkUserDataScope(Long userId) {
//        if (!SysUser.isAdmin(SecurityUtils.getUserId()))
//        {
//            SysUser user = new SysUser();
//            user.setUserId(userId);
//            List<SysUser> users = SpringUtils.getAopProxy(this).selectUserList(user);
//            if (StringUtils.isEmpty(users))
//            {
//                throw new ServiceException("没有权限访问用户数据！");
//            }
//        }
    }

    public boolean checkUserNameUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = sysUserMapper.checkUserNameUnique(user.getUserName());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    public boolean checkPhoneUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = sysUserMapper.checkPhoneUnique(user.getPhonenumber());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验email是否唯一
     *
     * @param user 用户信息
     * @return
     */
    public boolean checkEmailUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = sysUserMapper.checkEmailUnique(user.getEmail());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    public int insertUser(SysUser user) {
        // 新增用户信息
        int rows = sysUserMapper.insertUser(user);
        // 新增用户与角色管理
        insertUserRole(user);
        return rows;
    }

    public void insertUserRole(SysUser user) {
        insertUserRole(user.getUserId(), user.getRoleIds());
    }

    public void insertUserRole(Long userId, Long[] roleIds) {
        if (StringUtils.isNotEmpty(roleIds)) {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<>(roleIds.length);
            for (Long roleId : roleIds) {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                list.add(ur);
            }
            sysUserRoleMapper.batchUserRole(list);
        }
    }

    public boolean checkUserAllowed(SysUser user) {
        return !StringUtils.isNotNull(user.getUserId()) || !user.isAdmin();
    }

    public int updateUser(SysUser user) {
        Long userId = user.getUserId();
        // 删除用户与角色关联
        sysUserRoleMapper.deleteUserRoleByUserId(userId);
        // 新增用户与角色管理
        insertUserRole(user);
        return sysUserMapper.updateUser(user);
    }

    public int deleteUserByIds(Long[] userIds) {
        for (Long userId : userIds) {
            checkUserAllowed(new SysUser(userId));
            checkUserDataScope(userId);
        }
        // 删除用户与角色关联
        sysUserRoleMapper.deleteUserRole(userIds);
        return sysUserMapper.deleteUserByIds(userIds);
    }

    public List<SysRole> selectRolesByUserId(Long userId) {
        List<SysRole> userRoles = sysRoleMapper.selectRolePermissionByUserId(userId);
        List<SysRole> roles = sysRoleMapper.selectRoleAll();
        for (SysRole role : roles) {
            for (SysRole userRole : userRoles) {
                if (role.getRoleId().longValue() == userRole.getRoleId().longValue()) {
                    role.setFlag(true);
                    break;
                }
            }
        }
        return roles;
    }

    public void insertUserAuth(Long userId, Long[] roleIds) {
        sysUserRoleMapper.deleteUserRoleByUserId(userId);
        insertUserRole(userId, roleIds);
    }
}
